import $ from "jquery";
import {composeHighlightFromViewstate, stringifyHighlighsToViewstate} from "~manager/viewstateManager";
import { store } from "~storage/store";

const updateColor = async (highlightId, viewstate, color=null,  colorTitle=null) => {
  let newColor = undefined;
  if (colorTitle){
    newColor = await getColorByTitle(colorTitle);
  } else {
    newColor = color || await cycleColor(highlightId);
  }
  // color = color || await cycleColor(highlightId);
  const highlights = $(`.highlighter--highlighted[data-highlight-id='${highlightId}']`);

  highlights.css('backgroundColor', newColor.color); // Change the background color attribute
  highlights.css('color', newColor.textColor || "inherit");

  const url = location.hostname + location.pathname;
  const highlightWithViewstate = await updateHighlightColor(url, viewstate, newColor.color, newColor.textColor); // update the value in the local storage
  for (let i=0; i<highlights.length; i++){
    highlights[i].setAttribute("viewstate", highlightWithViewstate.viewstate);
  }
  await store(url, highlightWithViewstate.viewstate);
}

const getColorByTitle = (colorTitle) => {
  return new Promise((resolve, _reject) => {
    chrome.runtime.sendMessage({ action: 'get-color-options' }, ({ response: colorOptions }) => {
      const colorOption = colorOptions.find((option) => option.title === colorTitle);
      resolve(colorOption);
    });
  });
}

// Find the current highlight color and return the next color in the list
const cycleColor = (highlightId) => {
  const highlightEl = document.querySelector(`.highlighter--highlighted[data-highlight-id='${highlightId}']`);
  const currentColor = highlightEl.style.backgroundColor;

  return new Promise((resolve, _reject) => {
    chrome.runtime.sendMessage({ action: 'get-color-options' }, ({ response: colorOptions }) => {
      // Find index by color rgb value (returns -1 if nothing found):
      const currentIndex = colorOptions.findIndex((color) => color.color === currentColor);
      const newColorOption = colorOptions[(currentIndex + 1) % colorOptions.length];
      resolve(newColorOption);
    });
  });
}

const updateHighlightColor = (url, viewstate, newColor, newTextColor) => {
  const highlight = composeHighlightFromViewstate(viewstate);
  if (newColor !== undefined && newColor !== null) {
    highlight.color = newColor;
    highlight.textColor = newTextColor;
  }
  highlight.viewstate = stringifyHighlighsToViewstate(highlight);

  return highlight;
}

export default updateColor;
